use std::{rc::Rc, cell::RefCell};

use crate::{instructions::base::Instruction, rtda::Frame};


// Add double
#[derive(Debug, Default)]
pub struct DADD {}

impl Instruction for DADD {
    fn execute(&mut self, frame: Rc<RefCell<Frame>>) {
        let stack = frame.borrow().get_operand_stack();
        let v2 = stack.borrow_mut().pop_double();
        let v1 = stack.borrow_mut().pop_double();
        let result = v1 + v2;
        stack.borrow_mut().push_double(result);
    }
}

// Add float
#[derive(Debug, Default)]
pub struct FADD {}

impl Instruction for FADD {
    fn execute(&mut self, frame: Rc<RefCell<Frame>>) {
        let stack = frame.borrow().get_operand_stack();
        let v2 = stack.borrow_mut().pop_float();
        let v1 = stack.borrow_mut().pop_float();
        let result = v1 + v2;
        stack.borrow_mut().push_float(result);
    }
}


// Add int
#[derive(Debug, Default)]
pub struct IADD {}

impl Instruction for IADD {
    fn execute(&mut self, frame: Rc<RefCell<Frame>>) {
        let stack = frame.borrow().get_operand_stack();
        let v2 = stack.borrow_mut().pop_int();
        let v1 = stack.borrow_mut().pop_int();
        let result = v1.wrapping_add(v2); // 允许溢出
        stack.borrow_mut().push_int(result);
    }
}

// Add long
#[derive(Debug, Default)]
pub struct LADD {}

impl Instruction for LADD {
    fn execute(&mut self, frame: Rc<RefCell<Frame>>) {
        let stack = frame.borrow().get_operand_stack();
        let v2 = stack.borrow_mut().pop_long();
        let v1 = stack.borrow_mut().pop_long();
        let result = v1.wrapping_add(v2); // 允许溢出
        stack.borrow_mut().push_long(result);
    }
}
